package com.shenmazg6.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.shenmazg6.utils.ResultResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

/**
 * @author 军哥
 * @version 1.0
 * @description: Sentinel
 * @date 2022/12/24 22:14
 */

@RestController
@RequestMapping(value = "/sentinel")
public class SentinelController {

    @PostMapping(value = "/helloWorld")
    public ResultResponse helloWorld() {

        try(Entry entry = SphU.entry("helloWorld")) {
            return ResultResponse.SUCCESS(System.currentTimeMillis());
        }
        catch (Exception e) {
            return ResultResponse.FAILED(403, "系统繁忙，请稍后再试！");
        }
    }

    /**
     * @PostConstruct 定义限流规则，构造函数执行完成后执行的方法，用来初始化限流规则
     */

    @PostConstruct
    public void initFlowRules() {
        ArrayList<FlowRule> flowRuleArrayList = new ArrayList<FlowRule>();

        FlowRule flowRule = new FlowRule();
        flowRule.setResource("helloWorld");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(1);

        flowRuleArrayList.add(flowRule);

        FlowRuleManager.loadRules(flowRuleArrayList);

    }

}
